<template>
	<view>
		<view class="item u-border-bottom media" :class="{ bast: item.adopttime > 0 }" v-for="(item, index) in answerList" :key="index">
			<view class="answer-icon" :style="[{ background: theme.bgColor }]" v-if="item.adopttime > 0"><view class="u-font-25">最佳答案</view></view>
			<view class="header" @click="goUser(item.user && item.user.id)">
				<image :src="item.user && item.user.avatar" mode="aspectFill"></image>
				<view class="u-flex-1 u-p-l-20">
					<view class="u-flex u-row-between">
						<view class="">
							<text class="username">{{ item.user && item.user.nickname }}</text>
							<u-tag
								class="u-m-l-10"
								v-if="item.user && item.user.title"
								:text="item.user.title"
								:bg-color="theme.lightColor"
								:border-color="theme.faBorderColor"
								:color="theme.bgColor"
								size="mini"
								type="primary"
							/>
						</view>
						<view class="text-muted">{{ item.create_date }}</view>
					</view>
					<view class="text-muted bio u-flex">
						<text class="u-line-1">{{ item.user && item.user.bio ? item.user.bio : vuex_bio }}</text>
					</view>
				</view>
			</view>
			<u-notice-bar class="margin-tb-sm margin-lr" padding="18rpx 0" :no-list-hidden="false" v-if="item.thanksList && item.thanksList.length > 0" :list="item.thanksList.map(item=>{ return item.reamrk })" mode="vertical" duration="4000" font-size="26" :volume-icon="false"></u-notice-bar>
			<view class="u-p-l-30 u-p-r-30 content_fmt">
				<u-parse
					v-if="!idAudio(item.content)"
					:html="item.content_fmt"
					:tag-style="vuex_parse_style"
					:domain="vuex_config.upload ? vuex_config.upload.cdnurl : ''"
				></u-parse>
				<fa-audio v-else :htmls="item.content"></fa-audio>
			</view>
			<!-- 付费查看 -->
			<view class="u-p-30 u-text-center" v-if="item.peep_status == 'unpaid'">
				<u-button
					hover-class="none"
					size="medium"
					type="primary"
					:custom-style="{ backgroundColor: btnBgColor(true), color: btnColor(true), border: '1px solid ' + theme.faBorderColor }"
					@click="articlePay(item)"
				>
					付费查看
				</u-button>
			</view>
			<view class="u-flex u-p-30">
				<view class="u-m-r-5">
					<u-button
						hover-class="none"
						type="primary"
						size="mini"
						:custom-style="{
							backgroundColor: btnBgColor(item.vote, 'up'),
							color: btnColor(item.vote, 'up'),
							border: '1px solid ' + theme.faBorderColor
						}"
						@click="answerVote(item, 'up')"
					>
						▲赞同 {{ item.voteup }}
					</u-button>
				</view>
				<view class="u-m-r-30">
					<u-button
						hover-class="none"
						type="primary"
						size="mini"
						:custom-style="{
							backgroundColor: btnBgColor(item.vote, 'down'),
							color: btnColor(item.vote, 'down'),
							border: '1px solid ' + theme.faBorderColor
						}"
						@click="answerVote(item, 'down')"
					>
						▼不赞同
					</u-button>
				</view>
				<view class="u-flex-2" @click="showRemark(item, index)">
					<u-icon name="chat"></u-icon>
					{{ item.comments > 0 ? `${item.comments} 条回复` : '添加回复' }}
				</view>
				<view class="more u-p-l-30" @click="remarkClick(index, item)"><u-icon name="more-dot-fill" size="35"></u-icon></view>
				<!--  -->
			</view>

			<!-- 回复列表 -->
			<view class="u-p-30" v-if="item.is_show">
				<view class="item u-m-b-30 u-p-b-30" :class="{ medias: item.adopttime > 0 }" v-for="(it, ik) in item.comment_list" :key="ik">
					<view class="header" @click="goUser(it.user && it.user.id)">
						<view class=""><image :src="it.user && it.user.avatar" mode="aspectFill"></image></view>
						<view class="u-flex-1 u-p-l-20">
							<view class="u-flex u-row-between">
								<view class="">
									<text class="username">{{ it.user && it.user.nickname }}</text>
									<u-tag
										class="u-m-l-10"
										v-if="it.user && it.user.title"
										:bg-color="theme.lightColor"
										:border-color="theme.faBorderColor"
										:color="theme.bgColor"
										:text="it.user.title"
										size="mini"
										type="primary"
									/>
								</view>
								<view class="text-muted">{{ it.create_date }}</view>
							</view>
							<view class="u-p-t-10 u-tips-color bios u-flex">
								<text class="u-line-1">{{ it.user && it.user.bio ? it.user.bio : vuex_bio }}</text>
							</view>
							<view class="u-p-t-10 content_fmt">
								<u-parse
									:html="it.content_fmt"
									:tag-style="vuex_parse_style"
									:domain="vuex_config.upload ? vuex_config.upload.cdnurl : ''"
								></u-parse>
							</view>
						</view>
					</view>
					<view class="bottom u-flex u-row-around u-tips-color u-p-15">
						<!-- 评论操作条 -->
						<view class="" v-for="(val, vky) in operate" :key="vky" @click="clickOperate(vky, ik, index, it, item)">
							<view class="u-flex bar-item">
								<u-icon :name="val.icon"></u-icon>
								<view class="u-p-l-5">{{ !vky ? it.voteup : val.text }}</view>
							</view>
						</view>
					</view>
				</view>
				<!-- 更多 -->
				<view class="label-primary u-p-10 u-text-center u-font-22 u-m-b-30" :style="[{ color: theme.bgColor }]" v-if="has_more" @click="moreComment(item)">
					加载更多
				</view>
				<view
					class="label-primary u-p-10 u-text-center u-font-22 u-m-b-30"
					:style="[{ color: theme.bgColor }]"
					v-if="item.comments"
					@click="openEdit(item, index)"
				>
					追加回复
				</view>
			</view>
		</view>
		<!-- 评论操作条 -->
		<u-popup v-model="remark" mode="bottom">
			<view class="">
				<u-grid class="u-p-t-30 u-p-b-30" :col="remarkLength" :border="false">
					<u-grid-item v-for="(item, index) in barList" :key="index" @click="remarkBarClick(index)">
						<u-icon :name="item.icon" :size="item.size"></u-icon>
						<view class="grid-text u-m-t-15">{{ item.text }}</view>
					</u-grid-item>
				</u-grid>
				<u-gap height="3" bg-color="#f4f6f8"></u-gap>
				<view class="u-p-30 u-text-center" @click="remark = false">取消</view>
			</view>
		</u-popup>
		<!-- 提示框 -->
		<u-modal v-model="show" :content="modal_content" :show-cancel-button="showCancel" @confirm="modalConfirm" title="温馨提示"></u-modal>
		<!-- 感谢 -->
		<fa-thanks @close="close" ref="faThank" type="answer" :source_id="source_id"></fa-thanks>
		<!-- 举报 -->
		<fa-report ref="faReport" :source_id="jb_id" :type="jb_type"></fa-report>
		<!-- 付费查看 -->
		<fa-order-pay ref="orderPay" type="answer" :money="answer_price" :source_id="answer_id" :score="answer_score" @successPay="successPay"></fa-order-pay>
		<!-- 编辑评论 -->
		<u-popup v-model="write_show" mode="bottom" border-radius="5" :zoom="false">
			<view class="sendMsg">
				<view class="header u-flex u-row-between u-p-l-30 u-p-r-30 u-p-t-20 u-p-b-20">
					<view class="">{{ write_type == 3 ? '编辑回复' : write_type == 2 ? '回复TA' : write_type == 1 ? '追加回复' : '添加回复' }}</view>
					<u-icon name="close" @click="closemsg"></u-icon>
				</view>
				<view class="u-p-30">
					<scroll-view scroll-y="true" class="scroll-Y" style="height: 550rpx;">
						<!-- #ifdef MP-WEIXIN || APP-PLUS || H5 -->
						<fa-editor ref="faContent"></fa-editor>
						<!-- #endif -->
						<!-- #ifdef MP-BAIDU || MP-ALIPAY -->
						<fa-markdown ref="faContent"></fa-markdown>
						<!-- #endif -->
					</scroll-view>
				</view>
				<fa-captchaparts
					label-position="left"
					ref="captcha"
					:ident="write_type == 3 ? edit_form.id : add_form.id"
					:custom-style="{ padding: '0 30rpx 30rpx' }"
					mode="postcomment"
					v-model="captcha"
				></fa-captchaparts>
				<view class="u-text-center u-p-b-30">
					<u-button
						hover-class="none"
						type="primary"
						:custom-style="{ width: '80%', backgroundColor: btnBgColor(true), color: btnColor(true) }"
						size="medium"
						@click="confirm"
					>
						提交保存
					</u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import { collection, vote } from '@/common/fa.mixin.js';
import {
	mapState
} from 'vuex';
export default {
	mixins: [collection, vote],
	name: 'fa-answer-item',
	props: {
		listData: {
			type: Array,
			default: []
		},
		detailId: {
			type: [String, Number],
			default: ''
		},
		//是否有最佳答案
		hasBast: {
			type: Boolean,
			default() {
				return false;
			}
		},
		//当前问题的用户id
		questionUserId: {
			type: [String, Number],
			default: ''
		},
		//事件名称
		eventName: {
			type: String,
			default: 'answerUpdate'
		}
	},
	computed: {
		...mapState(['user']),
		remarkLength() {
			return this.barList.length <= 3 ? 3 : 4;
		},
		idAudio() {
			return item => {
				return item.indexOf('<audio') != -1 && item.indexOf('duration=') != -1;
			};
		}
	},
	watch: {
		listData: {
			handler: function(newValue, oldValue) {
				//支付宝多次更新
				this.answerList = newValue;
			},
			immediate: true
		}
	},
	mounted() {
		// 评论操作条
		//如果是管理员，追加操作条
		if (this.vuex_isAdmin) {
			this.barList = this.barList.concat([
				{
					icon: 'edit-pen-fill',
					text: '补充回答',
					id: 3,
					size: 50
				},
				{
					icon: 'checkmark',
					text: '采纳此回答',
					id: 4,
					size: 50
				},
				{
					icon: 'trash-fill',
					text: '删除',
					id: 5,
					size: 50
				}
			]);

			this.operate = this.operate.concat([
				{
					icon: 'edit-pen-fill',
					text: '编辑'
				},
				{
					icon: 'trash-fill',
					text: '删除'
				}
			]);
		}
		//如果是自己提问，且没有最佳答案，追加采纳操作按钮
		if (this.questionUserId == this.user.id && !this.hasBast) {
			this.addBarList();
		}
	},
	data() {
		return {
			answer_price: 0,
			answer_id: 0,
			answer_score: 0,
			answerList: [],
			show: false,
			write_show: false,
			write_type: 0,
			modal_content: '',
			showCancel: true,
			modal_status: 'delete_answer',
			barList: [
				{
					icon: 'bookmark-fill',
					text: '收藏',
					id: 0,
					size: 45
				},
				{
					icon: 'heart-fill',
					text: '感谢',
					id: 1,
					size: 45
				},
				{
					icon: 'warning-fill',
					text: '举报',
					id: 2,
					size: 45
				}
			],
			operate: [
				{
					icon: 'thumb-up',
					text: '点赞'
				},
				{
					icon: 'chat',
					text: '回复'
				},
				{
					icon: 'warning-fill',
					text: '举报'
				}
			],
			jb_id: 0,
			jb_type: '',
			source_id: 0,
			page: 1,
			remark: false,
			remarkIndex: 0,
			add_form: {},
			edit_form: {},
			delete_form: {},
			lsItem: {}, //临时
			has_more: false,
			captcha: ''
		};
	},
	methods: {
		close() {
			this.$emit('update', 'update');
		},
		articlePay(item) {
			this.answer_id = item.id;
			this.answer_price = item.price;
			this.answer_score = item.score;
			this.$refs.orderPay.show();
		},
		successPay() {
			this.$emit('update', 'update');
		},
		goUser(id) {
			if (!id) return;
			this.$wanlshop.to(`/pages/community/user/index?user_id=${id}`);
		},
		//答案点赞，或取消，或给错
		answerVote(item, type) {
			if (item.vote != type) {
				this.goVoteCreate(item, 'answer', type);
			} else {
				this.goVoteDelete(item, 'answer', type);
			}
		},
		//更多评论操作条
		remarkClick(index, item) {
			if (this.user.id == item.user.id && !this.vuex_isAdmin) {
				let isAdd = false;
				this.barList.forEach(item => {
					if (item.id == 3) {
						isAdd = true;
					}
				});
				if (!isAdd) {
					this.barList.push({
						icon: 'edit-pen-fill',
						text: '补充回答',
						id: 3,
						size: 50
					});
				}
			} else if (!this.vuex_isAdmin) {
				//不是自己的需要移除掉
				this.barList.forEach((item, index) => {
					if (item.id == 3) {
						this.barList.splice(index, 1);
					}
				});
			}
			this.remarkIndex = index;
			this.$set(this.barList[0], 'text', this.answerList[index].collected ? '已收藏' : '收藏');
			this.remark = true;
		},
		closemsg() {
			this.write_show = false;
		},
		//modal 确认按钮
		modalConfirm() {
			if (this.modal_status == 'delete_answer') {
				this.goAnswerDelete();
			} else if (this.modal_status == 'delete_comment') {
				this.goCommentDelete();
			}
		},
		//展示回复
		showRemark: async function(item, index) {
			this.add_form.id = item.id;
			this.add_form.index = index;
			if (!item.is_get) {
				let res = await this.$api.getCommentList({
					id: item.id,
					type: 'answer'
				});
				if (!res.code) {
					this.$u.toast(res.msg);
					return;
				}
				item.comment_list = res.data.data;
				this.has_more = res.data.current_page < res.data.last_page;
				item.is_get = true;
			}
			if (!item.comments) {
				//添加
				this.write_show = true;
				this.write_type = 0; //添加回复
				return;
			} else {
				item.is_show = !item.is_show;
			}
		},
		//开启回复
		openEdit(item, index) {
			this.write_show = true;
			this.write_type = 1; //追加【添加】
			this.add_form.id = item.id;
			this.add_form.index = index;
		},
		addBarList() {
			// 评论操作条增加
			this.barList = this.barList.concat([
				{
					icon: 'checkmark',
					text: '采纳此回答',
					id: 4,
					size: 50
				}
			]);
		},
		//删除答案
		goAnswerDelete: async function() {
			let res = await this.$api.goAnswerDelete({
				id: this.answerList[this.remarkIndex].id
			});
			this.$u.toast(res.msg);
			if (!res.code) {
				return;
			}
			this.answerList.splice(this.remarkIndex, 1);
		},
		//采纳此答案
		getQuestionAdopt: async function() {
			let res = await this.$api.getQuestionAdopt({
				question_id: this.detailId,
				best_answer_id: this.answerList[this.remarkIndex].id
			});
			this.$u.toast(res.msg);
			if (!res.code) {
				return;
			}
			this.$emit('update', 'update');
		},
		//评论操作条
		remarkBarClick(index) {
			this.remark = false;
			let id = this.answerList[this.remarkIndex].id;
			switch (this.barList[index].id) {
				case 0: //收藏
					if (this.answerList[this.remarkIndex].collected) {
						//已收藏，
						this.goCollectionDelete(this.answerList[this.remarkIndex], 'answer');
					} else {
						this.goCollectionCreate(this.answerList[this.remarkIndex], 'answer');
					}
					break;
				case 1: //感谢
					this.source_id = id;
					this.$refs.faThank.show();
					break;
				case 2: //举报
					this.jb_id = this.answerList[this.remarkIndex].id;
					this.jb_type = 'answer';
					this.$refs.faReport.show();
					break;
				case 3: //补充回答
					//监听答案更新事件
					uni.$once(this.eventName, res => {
						this.$set(this.answerList[res.index], 'content_fmt', res.data.content_fmt);
						this.$set(this.answerList[res.index], 'content', res.data.content);
					});
					this.$wanlshop.to(`/pages/community/question/answer?id=${id}&index=${this.remarkIndex}&event=${this.eventName}`)
					break;
				case 4: //采纳此答案
					this.getQuestionAdopt();
					break;
				case 5: //删除
					this.modal_status = 'delete_answer';
					this.modal_content = '确认删除?';
					this.show = true;
					break;
			}
		},
		//加载更多评论
		moreComment: async function(item) {
			let res = await this.$api.getCommentList({
				page: ++this.page,
				type: 'answer',
				id: item.id
			});
			if (!res.code) {
				this.$u.toast(res.msg);
				return;
			}
			item.comment_list = item.comment_list.concat(res.data.data || []);
			this.has_more = res.data.current_page < res.data.last_page;
		},
		//提交
		confirm: async function() {
			let content = await this.$refs.faContent.getData();

			if (this.write_type == 3) {
				this.edit_form.content = content;
				this.edit_form.captcha = this.captcha;
				let res = await this.$api.goCommentUpdate(this.edit_form);
				this.$u.toast(res.msg);
				if (!res.code) {
					this.$refs.captcha.getCaptcha();
					return;
				}
				this.lsItem.content_fmt = res.data.content_fmt;
				this.lsItem.content = res.data.content;
			} else {
				//都是添加
				let res = await this.$api.goCommentPost({
					...this.add_form,
					type: 'answer',
					content: content,
					captcha: this.captcha,
					subscribe: 1 //有人回复邮箱通知
				});
				this.$u.toast(res.msg);
				if (!res.code) {
					this.$refs.captcha.getCaptcha();
					return;
				}
				let index = this.add_form.index;
				this.answerList[index].comment_list.push(res.data.comment);
				this.$set(this.answerList[index], 'comments', this.answerList[index].comments + 1);
				this.$refs.faContent.setData('');
			}
			this.closemsg();
		},
		//删除评论
		goCommentDelete: async function() {
			let res = await this.$api.goCommentDelete(this.delete_form);
			this.$u.toast(res.msg);
			if (!res.code) {
				return;
			}
			let index = this.delete_form.index;
			this.answerList[index].comment_list.splice(this.delete_form.key, 1);
			this.$set(this.answerList[index], 'comments', this.answerList[index].comments - 1);
		},
		//回复操作条事件
		clickOperate(type, ik, index, it, item) {
			switch (type) {
				case 0:
					if (it.vote == 'up') {
						this.goVoteDelete(it, 'comment');
					} else {
						this.goVoteCreate(it, 'comment');
					}
					break;
				case 1:
					this.write_show = true;
					this.write_type = 2;
					this.add_form.id = item.id;
					this.add_form.index = index;
					//回复[添加]
					this.$nextTick(() => {
						// #ifdef MP-WEIXIN || APP-PLUS || H5
						this.$refs.faContent.setData(`@${it.user.nickname}&nbsp;`);
						// #endif
						// #ifdef MP-BAIDU || MP-ALIPAY
						this.$refs.faContent.setData(`@${it.user.nickname} `);
						// #endif
					});
					break;
				case 2:
					this.jb_id = it.id;
					this.jb_type = 'comment';
					this.$refs.faReport.show();
					break;
				case 3: //编辑
					this.write_show = true;
					this.write_type = 3;
					this.edit_form = {
						id: it.id,
						content: ''
					};
					this.lsItem = it;
					this.$nextTick(() => {
						// #ifdef MP-WEIXIN || APP-PLUS || H5
						this.$refs.faContent.setData(it.content_fmt);
						// #endif
						// #ifdef MP-BAIDU || MP-ALIPAY
						this.$refs.faContent.setData(it.content);
						// #endif
					});
					break;
				case 4: //删除
					this.delete_form = {
						id: it.id,
						key: ik,
						index: index
					};
					this.modal_status = 'delete_comment';
					this.modal_content = '确认删除?';
					this.show = true;
					break;
			}
		}
	}
};
</script>

<style lang="scss">
.header {
	display: flex;
	padding: 30rpx;

	image {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
	}

	.username {
		font-weight: bold;
	}
	.bio {
		width: 500rpx;
	}
	.bios {
		width: 450rpx;
	}
}

.bar-item {
	background: rgba(0, 132, 255, 0.1);
	padding: 5rpx 20rpx;
	border-radius: 5rpx;
	font-size: 20rpx;
}

.media.bast {
	border-color: #fbf2ca;
	background: #fbf2ca;
	background-size: 140rpx 140rpx;
	overflow: hidden;
}
.media.bast .answer-icon {
	width: 350rpx;
	position: absolute;
	right: -120rpx;
	transform: rotate(45deg);
	z-index: 0;
	top: 32rpx;
	text-align: center;
	height: 50rpx;
	line-height: 50rpx;
	color: #ffffff;
	opacity: 0.5;
	letter-spacing: 5rpx;
}
.media .item {
	background: #f2f7fd;
}
.media .medias {
	background: #efe7c3;
}
.content_fmt {
	line-height: 45rpx;
	word-break: break-word;
}
.label-primary {
	background: rgba(0, 132, 255, 0.1);
	border-color: transparent;
}
// 弹出层的公共样式
.sendMsg {
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	.header {
		border-bottom: 1px solid #eee;
		background-color: #f8f8f8;
	}
}
</style>
